﻿using Microsoft.Xna.Framework.Net;
using RaptorEngine.Components;

namespace RaptorEngine
{
    public class SumoNetwork
    {
        #region Settings
        public int MAX_LOCAL_GAMERS = 2;
        public int MAX_NETWORK_GAMERS = 4;
        #endregion

        public PacketWriter PacketWriter { get; set; }
        public PacketReader PacketReader { get; set; }

        public SumoNetwork(){}

        public void SumoPacketWriter(int entityID)
        {
            // Write entityID
            PacketWriter.Write(entityID);

            // Write each networkable component
            foreach (Component component in GameEngine.Instance.Scene.PeekScene().GetEntity(entityID).Components.Values)
            {
                if (component.ComponentType == ComponentType.Movable)
                {
                    MovementWriter(entityID);
                }
            }
        }

        public void SumoPacketReader(int entityID)
        {
            while (PacketReader.Position != PacketReader.Length)
            {
                // Read componentID
                int componentID = PacketReader.ReadInt32();

                if (componentID == 1)
                    MovementReader(entityID);
            }
        }

        // Subwriters for each component
        #region ComponentWriters
        private void MovementWriter(int entityID)
        {
            foreach (Entity entity in GameEngine.Instance.Scene.PeekScene().Entities)
            {
                if (entity.Id == entityID)
                {
                    PacketWriter.Write(entityID);
                    PacketWriter.Write(entity.Position);
                }
            }
        }
        #endregion

        // Subreaders for each component. 
        #region ComponentReaders
        private void MovementReader(int entityID)
        {
            foreach (Entity entity in GameEngine.Instance.Scene.PeekScene().Entities)
            {
                if (entity.Id == entityID)
                {
                    entity.Position = PacketReader.ReadVector3();
                }
            }
        }
        #endregion
    }
}
